﻿using L.EntityFramework;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NB.MGJ.Service.CodeManage
{
    public   class CodeCommonService:BaseService
    {

        public BaseRepository _baseRepository = new BaseRepository();

        public CodeCommonService()
        {

        }

        public int GetTableEnterpriseId(int eid)
        {
            if (eid < 10000)
            {
                return eid;
            }

            string sql = "select * from organization_enterprise where ID=" + eid;
            var result = _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(sql).ToList().FirstOrDefault();
            if (result.HeadId.HasValue)
            {
                return result.HeadId.Value;
            }
            return 0;

            //int headId = 0;
            //if (eid < 10000)
            //{
            //    headId = eid;
            //}
            //else
            //{
            //    string sql = "select * from organization_enterprise where ID=" + eid;
            //    var result = _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(sql).ToList().FirstOrDefault();
            //    headId=Convert.ToInt32(result.HeadId);
            //}
            //return headId;
        }


        


        public string GetTableName(int eid,string CodeBatch)
        {
            ///10000以下的机构都是总部机构
            string prefix = "nbcodemain.antifake_digitcode";
            string eCode=string.Empty;
            string tableEid=string.Empty;
            string tableName=string.Empty;
            if (eid < 10000)
            {
                eCode=Convert.ToString(eid).PadLeft(4,'0');
            }
            else
            {
              tableEid=GetTableEnterpriseId(eid).ToString();
              eCode=tableEid.PadLeft(4,'0');
            }
            tableName=prefix+eCode+CodeBatch;
            return tableName;
        }




        /// <summary>
        /// 获取某一批次码的第一个码
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="codeBatch"></param>
        public CodeManage_GenCode GetCodeBatchFirstOrDefaultCodeModel(int eid, string codeBatch)
        {
            string tableName = GetTableName(eid, codeBatch);

            var sql = "select * from " + tableName + " where ID=1 ";

            return _baseRepository.ExecuteSqlCollection<CodeManage_GenCode>(sql).FirstOrDefault();

            //var result = _baseRepository.ExecuteSqlCollection<CodeManage_GenCode>(sql).ToList().FirstOrDefault();

            //return result;
        }




    }
}
